package com.m3839.sdk.ym.widget

import android.content.Context
import android.text.TextUtils
import android.util.AttributeSet
import android.view.KeyEvent
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import com.m3839.sdk.ym.ext.getLayoutId

/**
 * Description:DigitKeyboard
 *
 * @author 陈宝阳
 * @create 2020/4/11 10: 21
 */
class DigitKeyboard @JvmOverloads constructor(
    context: Context?,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : LinearLayout(context, attrs, defStyleAttr), View.OnClickListener {
    private var mListener: DigitKeyboardClickListener? = null

    /**
     * 设置键盘子View的点击事件
     */
    private fun setChildViewOnclick(parent: ViewGroup) {
        val childCount = parent.childCount
        for (i in 0 until childCount) {
            // 不断的递归设置点击事件
            val view = parent.getChildAt(i)
            if (view is ViewGroup) {
                setChildViewOnclick(view)
                continue
            }
            view.setOnClickListener(this)
        }
    }

    override fun onClick(v: View) {
        if (v is TextView) {
            // 如果点击的是TextView
            val number = v.text.toString()
            if (!TextUtils.isEmpty(number) && HIDE != number) {
                if (mListener != null) {
                    // 回调
                    mListener!!.click(number)
                }
            } else {
                visibility = View.GONE
                mListener!!.hidKeyBoard()
            }
        } else if (v is ImageView) {
            // 如果是图片那肯定点击的是删除
            if (mListener != null) {
                mListener!!.delete()
            }
        }
    }

    /**
     * 拦截back键的响应事件
     *
     * @param event 系统按键事件
     */
    fun dispatchKeyEventInFullScreen(event: KeyEvent?): Boolean {
        return if (event == null) {
            false
        } else when (event.keyCode) {
            KeyEvent.KEYCODE_BACK -> {
                if (isShown) {
                    visibility = View.GONE
                    mListener!!.hidKeyBoard()
                    return true
                }
                false
            }
            else -> false
        }
    }

    /**
     * 设置键盘的点击回调监听
     */
    fun setOnDigitKeyboardClickListener(listener: DigitKeyboardClickListener?) {
        mListener = listener
    }

    /**
     * 点击键盘的回调监听
     */
    interface DigitKeyboardClickListener {
        fun click(number: String?)
        fun delete()
        fun hidKeyBoard()
    }

    companion object {
        private const val HIDE = "收起"
    }

    init {
        View.inflate(context, getLayoutId("ym_digit_keyboard"), this)
        setChildViewOnclick(this)
    }
}